<template>
  <div class="ViewFile">
    <el-upload class="upload-big" ref="uploadRef" drag :auto-upload="false" :show-file-list="false" :limit="1"
      :on-change="uploadSectionFile">
      <div>
        <div v-if="modelValue">
          <img v-if="showType === 'image'" :src="`${modelValue}`" />
          <video v-else :src="modelValue" autoplay muted loop controls></video>
        </div>
        <div class="el-upload-des" v-else>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽图片到此处或者点击上传</div>

          <div class="el-upload__tip">
            *文件限至为{{ typeUploadList.toString() }}格式，
            <!-- 大小不超过{{ size }}M -->
          </div>
        </div>
      </div>
    </el-upload>
    <el-progress v-if="showProgress" :percentage="progress" />
  </div>
</template>

<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import router from '@/router'
import { uploadFile } from '@/api/file';
import { VITE_APP_IMAGE_BASE_URL as baseImage } from '@/utils/base';


const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  typeUploadList: {
    type: Array as any,
    default: () => []
  },
  size: {
    type: Number,
    default: 40,
  },
  showType: {
    type: String,
    default: 'image',
  },
  showProgress: {
    type: Boolean,
    default: true,
  },
})

const emit = defineEmits(['update:modelValue'])
const { modelValue, typeUploadList, showType } = toRefs(props)
const { size } = toReactive(props)
const uploadRef = ref(ElUpload);
const progress = ref(0)
let timer: any = null

function uploadSectionFile(file: any) {
  uploadRef.value.clearFiles();
  // const isJPG = typeUploadList.indexOf(file.raw.type) !== -1;
  // const isLtM = file.size / 1024 / 1024 < size;
  let typeMismatch = typeUploadList.value.some((typeEle: any) => {
    return file.raw.type.includes(typeEle)
  });
  if (!typeMismatch) {
    let str = typeUploadList.value.join(', ');
    ElMessage.warning(`文件必须为 ${str} 类型`);
    return false; // 不符合要求的文件类型直接返回 false，打断循环
  }
  // if (!isLtM) {
  //   ElMessage.warning(`上传图片大小不能超过 ${size}MB!`);
  //   return;
  // }
  timer = setInterval(() => {
    progress.value += 10
    if (progress.value >= 100) {
      progress.value = 99
    }
  }, 1000)

  uploadFile({ file: file.raw, contentType: file.raw.type }).then((res: any) => {
    let url = `${baseImage}${res.data}`;
    uploadSuccess()
    emit('update:modelValue', url)
  }).catch(() => {
    uploadError()
  })
}

function uploadSuccess() {
  progress.value = 100
  clearInterval(timer)
  ElMessage.success('操作成功');
  setTimeout(() => {
    progress.value = 0
  }, 2000)
}

function uploadError() {
  progress.value = 0
  clearInterval(timer)
  ElMessage.error('操作失败');
}

onMounted(async () => {

});

// 在组件即将卸载前取消定时器  
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
});

</script>

<style lang="scss" >
.upload-big {
  margin-bottom: 10px;

  .el-upload {
    padding: 0;
    width: 400px;
    // height: 200px;
  }

  .el-upload-dragger {


    .el-upload-des {}

    video {
      width: 100%;
      height: 100%;
    }

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
